package com.goodfox.web.generic.account.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.account.service.AccountService;
import com.goodfox.web.generic.authority.service.PowerService;
import com.goodfox.web.generic.organization.entity.Organization;
import com.goodfox.web.generic.organization.service.OrganizationService;
import com.goodfox.web.generic.provide.entity.Pager;
import com.goodfox.web.generic.provide.exception.EntityValidateException;
import com.goodfox.web.generic.provide.service.EntityService;
import com.goodfox.web.generic.provide.service.ExcelTemplateService;
import com.goodfox.web.generic.provide.util.ParameterUtil;
import com.goodfox.web.generic.provide.util.AttributeUtil;

/**
 * 组织机构管理Controller类，封装全部与组织机构管理相关的action请求链接
 * @author qin gt
 *
 */
@Controller
@RequestMapping("/account")
public class AccountController {

	/** log4j日志器 */
	private Logger logger=Logger.getLogger(AccountController.class);
	
	/** 人员账号Service */
	@Autowired
	private AccountService accountService;
	
	/** 组织机构Service */
	@Autowired
	private OrganizationService organizationService;
	
	/** 权限Service */
	@Autowired
	private PowerService powerService;
	
	/** excel文件操作Service */
	@Autowired
	private ExcelTemplateService excelTemplateService;
	
	/** 实体Service */
	@Autowired
	private EntityService entityService;

	
	/**
	 * 进入组织机构查找带回页面
	 * @return 目标页面
	 */
	@RequestMapping(value="goOrganizationLookup.shtml")
	public String goOrganizationLookup(HttpServletRequest request,ModelMap model){
		logger.info("进入组织机构查找带回页面");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
	    	return "organization/organizationLookup";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}

	/**
	 * 进入人员管理首页
	 * @return 目标页面
	 */
	@RequestMapping(value="goAccountIndex.shtml")
	public String goAccountIndex(HttpServletRequest request,ModelMap model){
		logger.info("进入人员管理首页");
		//判断是否有权限
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
		    model.put("curActOrgId", loginAccount.getOrgId());
		    //当前页
			int currentPage=1;
			if(!ParameterUtil.getReqParaValue(request,"pageNum").equals("")){
				currentPage=Integer.parseInt(ParameterUtil.getReqParaValue(request,"pageNum"));
			}
			//每页多少条
			int numPerPage=15;
			if(!ParameterUtil.getReqParaValue(request,"numPerPage").equals("")){
				numPerPage=Integer.parseInt(ParameterUtil.getReqParaValue(request,"numPerPage"));
			}
			//查询条件
		    Map queryMap=entityService.fillQueryMap(request,model);
			if(queryMap.get("orgList")==null || ((List)queryMap.get("orgList")).size()==0){
				queryMap.put("orgId", loginAccount.getOrgId());
				queryMap.put("orgList", null);
			}
			Pager<Account> pager=accountService.queryAccountPager(currentPage, numPerPage, queryMap);
			model.put("actList", pager.getEntityList());
			
			model.put("totalCount", pager.getAllCount());
			model.put("currentPage", currentPage);
			model.put("numPerPage", numPerPage);
			
			return "account/accountIndex";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 进入人员新增页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="goAccountAdd.shtml")
	public String goAccountAdd(HttpServletRequest request,ModelMap model){
		logger.info("进入人员新增页面");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			model.put("sexList", AttributeUtil.queryAttrListByType("性别"));
			model.put("roleList", accountService.queryRoleListByScope(loginAccount.getRole().getRoleScope()));
			model.put("org", loginAccount.getActOrganization());
			return "account/accountAdd";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行人员新增
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="accountAdd.shtml")
	@ResponseBody
	public Map accountAdd(HttpServletRequest request){
		logger.debug("执行人员新增");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "accountHome");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "closeCurrent");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				String actName=ParameterUtil.getReqParaValue(request, "act_add_actName");
				if(accountService.isHave(actName)){
					message="新增失败:此用户名已存在！";
				}else{
					Account entity=(Account)entityService.fillEntity(request,Account.class);
					accountService.addAccount(entity,request.getSession().getAttribute("loginLogId").toString());
					statusCode="200";
					message="新增成功！";
				}
			}catch(EntityValidateException evex){
				message="新增失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("accountAdd异常：",ex);
				message="新增失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("accountAdd rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入人员修改信息页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="goAccountModify.shtml")
	public String goAccountModify(HttpServletRequest request,ModelMap model){
		logger.info("进入人员修改信息页面");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			Account account = accountService.getAccount(ParameterUtil.getReqParaValue(request, "actId"));
			model.put("account", account);
			model.put("sexList", AttributeUtil.queryAttrListByType("性别"));
			//当前用户的组织机构对象
			Organization org = organizationService.getOrganization(loginAccount.getOrgId());
			model.put("roleList", accountService.queryRoleListByScope(loginAccount.getRole().getRoleScope()));
			
			return "account/accountModify";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行人员更新
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="accountModify.shtml")
	@ResponseBody
	public Map accountModify(HttpServletRequest request){
		logger.info("执行人员更新");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "accountHome");
		rspMap.put("callbackType", "update");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Account newEny=(Account)entityService.fillEntity(request,Account.class);
				Account oldEny=accountService.getAccount(newEny.getActId());
				accountService.modifyAccount(oldEny,newEny,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="更新成功！";
			}catch(EntityValidateException evex){
				message="更新失败:"+evex.getMessage()+"！";
			}catch(Exception ex){
				logger.error("accountModify异常：",ex);
				message="更新失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("accountModify rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行人员移除
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="accountRemove.shtml")
	@ResponseBody
	public Map accountRemove(HttpServletRequest request){
		logger.info("执行人员移除");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "reload");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Account entity=accountService.getAccount(ParameterUtil.getReqParaValue(request, "actId"));
				if(loginAccount.getActId().equals(entity.getActId())){
					message="您正使用该用户登录系统，不能移除！";
				}else{
					accountService.removeAccount(entity,request.getSession().getAttribute("loginLogId").toString());
					statusCode="200";
					message="移除成功！";
				}
			}catch(Exception ex){
				logger.error("accountRemove异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("accountRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行人员批量移除
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping(value="accountRemoveBat.shtml")
	@ResponseBody
	public Map accountRemoveBat(HttpServletRequest request){
		logger.info("执行人员批量移除");
		Map rspMap = new HashMap();
		rspMap.put("navTabId", "");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "reload");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				message="";
				String[] actIds=request.getParameterValues("actIds");
				for(String actId:actIds){
					Account entity=accountService.getAccount(actId);
					if(loginAccount.getActId().equals(entity.getActId())){
						message+="您正使用"+entity.getMemName()+"登录系统，不能移除！ ";
					}else{
						accountService.removeAccount(entity,request.getSession().getAttribute("loginLogId").toString());
						message+=entity.getMemName()+"移除成功！ ";
					}
				}
				statusCode="200";
			}catch(Exception ex){
				logger.error("accountRemove异常：",ex);
				message="移除失败:发生异常！";
			}
		}
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("accountRemove rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 进入人员查看信息页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="goAccountDetail.shtml")
	public String goAccountDetail(HttpServletRequest request,ModelMap model){
		logger.info("进入人员查看信息页面");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			Account account = accountService.getAccount(ParameterUtil.getReqParaValue(request, "actId"));
			model.put("account", account);
			model.put("sexList", AttributeUtil.queryAttrListByType("性别"));
			
			return "account/accountDetail";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 判断账号是否存在
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("isHave.shtml")
	@ResponseBody
	public boolean isHave(HttpServletRequest request) {
		boolean have=false;
		try{
			String actName = ParameterUtil.getReqParaValue(request, "actName");
			if(accountService.isHave(actName)){//存在
				have=true;
			}
		}catch(Exception ex){
			logger.error("判断账号存在异常：", ex);
		}
		return have;
	}
	
	/**
	 * 进入用户密码修改页面
	 * @param request
	 * @param model
	 * @return  目标页面
	 */
	@RequestMapping("goModifyPassword.shtml")
	public String goModifyPassword(HttpServletRequest request,ModelMap model){
		logger.info("进入用户密码修改页面");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			model.put("account",loginAccount);
			return "account/accountPwdModify";
	    }else{
	    	return "redirect:/login/logout.shtml";
	    }
	}
	
	/**
	 * 执行用户密码修改
	 * @param reqMap
	 * @param request
	 * @return
	 */
	@RequestMapping("modifyPassword.shtml")
	@ResponseBody
	public Map modifyPassword(HttpServletRequest request){
		logger.info("执行用户密码修改");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "accountHome");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！ ";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				String actName = ParameterUtil.getReqParaValue(request, "pwd_modify_actName");
				String oldActPwd = ParameterUtil.getReqParaValue(request, "pwd_modify_oldActPwd");
				Account oldEny = accountService.getAccountByNamePwd(actName, oldActPwd);
				if(oldEny!=null){
					Account newEny=(Account)entityService.fillEntity(request,Account.class);
					accountService.modifyPassword(oldEny,newEny,request.getSession().getAttribute("loginLogId").toString());
					statusCode="200";
					message="密码修改成功！ ";
				}else{
					message="旧密码错误，请重新输入！ ";
				}
			}catch(Exception ex){
				logger.error("modifyPassword异常", ex);
				message="密码修改失败:发生异常！ ";
			}
	    }
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("modifyPassword rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 重置用户密码
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("resetPassword.shtml")
	@ResponseBody
	public Map resetPassword(HttpServletRequest request) {
		logger.info("执行密码重置");
		Map rspMap=new HashMap();
		rspMap.put("navTabId", "accountHome");
		rspMap.put("rel", "");
		rspMap.put("callbackType", "");
		rspMap.put("forwardUrl", "");
		String statusCode="300";
		String message="无此权限！";
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
			try{
				Account oldEny=accountService.getAccount(ParameterUtil.getReqParaValue(request, "actId"));
				Account newEny=(Account)entityService.fillEntity(ParameterUtil.getReqParaMap(request),Account.class);
				accountService.modifyPassword(oldEny,newEny,request.getSession().getAttribute("loginLogId").toString());
				statusCode="200";
				message="已经将密码重置为初始密码："+ParameterUtil.getReqParaValue(request, "actPassword")+"！";
			}catch(Exception ex){
				logger.error("resetPassword异常：", ex);
				message="密码重置失败:发生异常！ ";
			}
	    }
		rspMap.put("statusCode", statusCode);
		rspMap.put("message", message);
		logger.debug("resetPassword rspMap:"+rspMap);
		return rspMap;
	}
	
	/**
	 * 执行导出
	 * @param request
	 * @param model 页面回写model
	 * @return 目标页面
	 */
	@RequestMapping(value="exportQuery.shtml")
	public void exportQuery(HttpServletRequest request,HttpServletResponse response,ModelMap model){
		logger.info("执行人员导出");
	    Account loginAccount=powerService.havePower(request);
	    if(loginAccount!=null){
		    Map queryMap=entityService.fillQueryMap(request,null);
		    String orgId = ParameterUtil.getReqParaValue(request, "act_query_orgId");
			if(orgId.equals("")){
				queryMap.put("orgId", loginAccount.getOrgId());
			}else{
				queryMap.put("orgId", orgId);
			}
			queryMap.put("actIds",ParameterUtil.getReqParaValue(request, "actIds"));
			
			List<Account> entityList=accountService.exportAccountList(queryMap);
			
			logger.info("entityList:"+entityList.size());
			
			excelTemplateService.webExpWorkbook(request, response, Account.class, entityList);
	    }
	}
	
}
